﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace DelCompanyDal
{
    public class Message
    {
        public static bool DelMessage(string conn, string sqltxt)
        {
            if (new QT.DBO.SqlDBHelper(conn).ExecuteNonQuery(sqltxt) > -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool WriteMessageInfo(string conn, string sqltxt, string urlfile, string picfile)
        {
            string[] sqlArray = sqltxt.Split('|');
            DataTable dt = new DataTable();
            foreach (string sql in sqlArray)
            {
                try
                {
                    dt = new QT.DBO.SqlDBHelper(conn).DataTable(sql);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return false;
                }

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (dt.Rows[i][j].ToString().Length > 0)
                        {
                            if (dt.Columns[j].ColumnName.ToUpper().Contains("URL"))
                            {
                                WriteLogs(urlfile, "dele " + (dt.Rows[i][j].ToString().StartsWith("/") ? dt.Rows[i][j].ToString().Remove(0, 1) : dt.Rows[i][j].ToString()));
                            }
                            else
                            {
                                if (!dt.Rows[i][j].ToString().ToLower().EndsWith(@"images/wutu.jpg"))
                                {
                                    WriteLogs(picfile, "dele " + (dt.Rows[i][j].ToString().StartsWith("/") ? dt.Rows[i][j].ToString().Remove(0, 1) : dt.Rows[i][j].ToString()));
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }

        public static DataTable GetMessageInfo(string conn, string sqltxt)
        {
            return new QT.DBO.SqlDBHelper(conn).DataTable(sqltxt);
        }

        private static void WriteLogs(string filepath, string txt)
        {
            FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.Read);
            StreamWriter text = new StreamWriter(fs);
            text.WriteLine(txt);
            text.Close();
            fs.Close();
            fs.Dispose();
        }
    }
}
